<%@page import="acceso.util.Escritor"%>
<%@page import="wf3.util.GeoIP"%>
<%@page import="acceso.util.WorkflowUtil"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%-- 
    Document   : geocode
    Created on : 04/05/2011, 12:32:02 PM
    Author     : Romulo Galindo Tanta
    parameters:
                            (latitud)       Latitud
                            (longitud)    Longitud
                            (editable)      Editable
                            (modo)          Modo
                            (radio)         Radio
                            (descripcion)   Descripcion
                            (type)          tipo
--%>
<%
    String mlat = WorkflowUtil.convertir_string(request.getParameter("latitud"), "0");
    String mlng = WorkflowUtil.convertir_string(request.getParameter("longitud"), "0");

    String latitud = "";
    String longitud = "";
    if ((mlat.isEmpty() | mlng.isEmpty()) | (mlat.contentEquals("0") | mlng.contentEquals("0"))) {
        GeoIP IP = WorkflowUtil.geoip(request.getRemoteAddr());
        if (IP != null) {
            latitud = IP.getLatitude();
            longitud = IP.getLongitude();
        } else {
            latitud = "-12.050839957146417";
            longitud = "-77.08269646679685";
        }
    } else {
        latitud = "" + WorkflowUtil.convertir_double(mlat, -8.113040);
        longitud = "" + WorkflowUtil.convertir_double(mlng, -79.034143);
    }
    boolean edit = WorkflowUtil.convertir_boolean(request.getParameter("editable"));

    int modo = WorkflowUtil.convertir_entero(request.getParameter("tipo"), 1);
    boolean zonas = (modo == 2 | modo == 4 | modo == 6) ? true : false;
    boolean credi = (modo == 3 | modo == 4) ? true : false;
    boolean ppeli = (modo == 5);
%>
<!--!DOCTYPE html-->
<html>
    <head>
        <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
        <script language="JavaScript" src="${pageContext.request.contextPath}/js/wfutil1.4.7.9-52.js" type="text/javascript"></script>
        <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&region=es&language=ES&libraries=geometry"></script>
        <script type="text/javascript" src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/maplabel/src/maplabel.js"></script>
        <!--script language="JavaScript" src="../js/maplabel.js" type="text/javascript"></script>
        <script language="JavaScript" src="../js/maplabel-compiled.js" type="text/javascript"></script-->
        <script type="text/javascript">
            var map;
            var marker;
            var lat;
            var lng;
            var metros = ${param.radio};
            //----------------------------------------------------------
            var infowindow = new google.maps.InfoWindow();
            var final = false;
            var puntos_finales = [];
            
            function initialize() {
                var latlng = new google.maps.LatLng(<%=latitud%>, <%=longitud%>);
                var Options = {
                    zoom: 16,
                    center: latlng,
                    mapTypeControlOptions: {
                        mapTypeIds: [google.maps.MapTypeId.HYBRID, google.maps.MapTypeId.SATELLITE, google.maps.MapTypeId.ROADMAP],
                        style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR
                    },
                    mapTypeId: google.maps.MapTypeId.ROADMAP,
                    overviewMapControl: true,
                    overviewMapControlOptions: {
                        opened: true
                    },
                    draggable: true,
                    streetViewControl: true,
                    scaleControl: true,
                    rotateControl: true,
                    panControl: true
                };
                lat = latlng.lat();
                lng = latlng.lng();

                map = new google.maps.Map(document.getElementById("map_canvas"), Options);
                marker = new google.maps.Marker({
                    position: latlng,
                    map: map,
                    icon: "../img/marker-ico.png",
                    draggable: <%=edit%>
                });

                google.maps.event.addListener(marker, 'dragend', function (event) {
                    var myLatLng = event.latLng;
                    lat = myLatLng.lat();
                    lng = myLatLng.lng();
                });
            }

            function center_position() {
                try {
                    map.setCenter(marker.getPosition());
                } catch (e) {
                }
            }

            function save_position() {
                parent.parent_close_popup_georeferencia_39(lat, lng);
            }

            function close_positicion() {
                parent.parent_close_popup_georeferencia_39(document.getElementById("t_lat").value, document.getElementById("t_lon").value);
            }

            //-------------------------------------

            function carga_zonas_peligrosas() {
            <%if (zonas) {%>
                document.title = "Cargando zonas peligrosas";
                var areas = getjsonfromurl(new getXMLObject(), "../GoogleService?xact=1");
                var poli_areas = [];
                var area_puntos = getjsonfromurl(new getXMLObject(), "../GoogleService?xact=10");
                for (var i = 0; i < areas.length; i++) {
                    //var area = areas[i].value;
                    var id_area = areas[i].id_areas;
                    var no_area = areas[i].no_areas;
                    var data = [];
                    var c = 0;
                    for (var o = 0; o < area_puntos.length; o++) {
                        if (area_puntos[o].id.id_zongeo == id_area) {
                            data[c] = new google.maps.LatLng(area_puntos[o].nu_geolat, area_puntos[o].nu_geolon);
                            c++;
                        }
                    }

                    poli_areas[i] = new google.maps.Polygon({
                        paths: data,
                        strokeColor: "#FF0000",
                        strokeOpacity: 1.0,
                        strokeWeight: .5,
                        fillColor: "#FF0000",
                        fillOpacity: 0.20,
                        area: areas[i].text,
                        id: areas[i].value,
                        seleccionado: false
                    });
                    poli_areas[i].setMap(map);

                    try {
                        var bounds = new google.maps.LatLngBounds();
                        for (var p = 0; p < data.length; p++) {
                            bounds.extend(data[p]);
                        }
                        console.log(bounds.getCenter());
                        var mapLabel = new MapLabel({
                            text: no_area,
                            position: bounds.getCenter(),
                            map: map,
                            //                            fontSize: font_size,
                            fontSize: 15,
                            align: 'center'
                        });
                    } catch (e) {
                        alert("Error:\n" + areas[i].no_areas)
                    }
                }

                document.title = "Listo";
            <%}%>
            }

            function infocredito(event) {
                infowindow.setContent("" + this.no_descri);
                infowindow.setPosition(this.position);

                infowindow.open(map);

            }

            function get_punto_final(puntos) {
                var punto = {
                    no_descri: puntos[0].no_descri,
                    nu_geolat: puntos[0].nu_geolat,
                    nu_geolon: puntos[0].nu_geolon,
                    id_georef: puntos[0].id_georef
                };
                var eli = [];
                for (var i = 1; i < puntos.length; i++) {
                    if (punto.nu_geolat == puntos[i].nu_geolat && punto.nu_geolon == puntos[i].nu_geolon) {
                        punto.no_descri = punto.no_descri + "<br/>" + puntos[i].no_descri;
                        eli[eli.length] = i;
                    }
                }

                for (var i = (eli.length - 1); i >= 0; i--) {
                    puntos.splice(eli[i], 1);
                }
                puntos.splice(0, 1);
                if (puntos.length == 0) {
                    final = true;
                }
                return punto;
            }

            function carga_todos_creditos() {
            <%if (credi) {%>

                var radio_credit = new google.maps.Circle({
                    center: marker.getPosition(),
                    radius: metros,
                    strokeColor: "#00CD00",
                    strokeOpacity: 1.0,
                    strokeWeight: .5,
                    fillColor: "#00CD00",
                    fillOpacity: 0.20
                });
                radio_credit.setMap(map);

                var todos = getjsonfromurl(new getXMLObject(), "../GoogleService?xact=11&p_nu_geolat=${param.latitud}&p_nu_geolon=${param.longitud}&p_nu_radmet=${param.radio}&p_ti_descri=${param.descripcion}");

                var v = 0;
                while (!final) {
                    v = v + 1;
                    console.log(">|1");
                    puntos_finales[puntos_finales.length] = get_punto_final(todos);
                    console.log(">|1");
                    if (v == 50)
                        final = true;
                }

                for (var i = 0; i < puntos_finales.length; i++) {
                    console.log(">" + puntos_finales[i].nu_geolat + "::" + puntos_finales[i].nu_geolon + ":::" + puntos_finales[i].no_descri);
                }


                var markers_creditos = [];
                if (todos != undefined) {
                    for (var i = 0; i < puntos_finales.length; i++) {
                        var punto = puntos_finales[i];
                        if (punto.nu_geolat == lat & punto.nu_geolon == lng) {
                            marker.setTitle("test");
                            google.maps.event.addListener(marker, 'click', infocredito);
                        } else {
                            var r = google.maps.geometry.spherical.computeDistanceBetween(marker.getPosition(), new google.maps.LatLng(punto.nu_geolat, punto.nu_geolon));
                            if (metros >= r) {
                                markers_creditos[markers_creditos.length] = new google.maps.Marker({
                                    position: new google.maps.LatLng(punto.nu_geolat, punto.nu_geolon),
                                    map: map,
                                    draggable: false,
                                    title: "" + punto.id_georef,
                                    no_descri: punto.no_descri
                                });
                                google.maps.event.addListener(markers_creditos[markers_creditos.length - 1], 'click', infocredito);
                            }
                        }
                    }
                }
            <%}%>
            }

            function carga_puntos_peligrosos() {
            <%if (ppeli) {%>
                var ppel = getjsonfromurl(new getXMLObject(), "../GoogleService?xact=12");
                for (var i = 0; i < ppel.length; i++) {
                    var ll = new google.maps.LatLng(ppel[i].nu_geolat, ppel[i].nu_geolon);
                    var rad = new google.maps.Circle({
                        center: ll,
                        radius: ppel[i].va_radios,
                        strokeColor: "#00CD00",
                        strokeOpacity: 1.0,
                        strokeWeight: .5,
                        fillColor: "#00CD00",
                        fillOpacity: 0.20,
                        title: ppel[i].no_zonpeg
                    });
                    rad.setMap(map);
                }
            <%}%>
            }

            function distance(lat1, lng1, lat2, lng2) {
                var radius = 3956.0 * 2; // miles

                var deltaLat = ToRadians(lat2 - lat1);
                var deltaLng = ToRadians(lng2 - lng1);
                var sinLat = Math.sin(0.5 * deltaLat);
                var sinLng = Math.sin(0.5 * deltaLng);
                var cosLat1 = Math.cos(ToRadians(lat1));
                var cosLat2 = Math.cos(ToRadians(lat2));
                var h1 = sinLat * sinLat + cosLat1 * cosLat2 * sinLng * sinLng;
                var h2 = Math.sqrt(h1);
                var h3 = 2 * Math.asin(Math.min(1, h2));
                var distance = radius * h3;
                console.log("distancia:" + distance);
                return distance;
            }

            function ToRadians(degree) {
                return (degree * (Math.PI / 180));
            }

            function load() {
                initialize();
                carga_zonas_peligrosas();
                carga_todos_creditos();
                carga_puntos_peligrosos();
            }

        </script>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <c:forEach items="${US.css_contenbody}" var="css">
            <link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath}/css/workflow/${css}?a=36"/>
        </c:forEach>
        <link rel="shortcut icon" href="${pageContext.request.contextPath}/img/georeferencia.png">
        <title>Acceso - Georefencia [${US}][${US.css_contenbody}]</title>
    </head>
    <body onload="load()" style="margin: 0px;">
        <div id="msg_panel" class="wait" style="display:none; height: 100px;">
            <table cellspacing="0" cellpadding="0" class="waitPopup_table" style="width: 94%; margin: 10px; background-image: url('../img/georeferencia.png'); background-position: left top;">
                <tr>
                    <td align="left" style="vertical-align: bottom; height: 20px;">
                        <div class="waitPopup_title">Georeferencia</div>
                    </td>
                </tr>
                <tr>
                    <td align="left" style="vertical-align: top; height: 20px;">
                        <div id="waitPopup_msg" class="waitPopup_msg">La georeferencia ha sido modificada</div>
                    </td>
                </tr>
                <tr>
                    <td style="text-align: right;">
                        <button id="msgbox_btn" class="boton" style="height: 27px; float: none;" onclick="window.close();">Aceptar</button>
                    </td>
                </tr>
            </table>
        </div>
        <table style="width: 100%; height: 100%" cellSpacing="0" cellPadding="1" border="0" class="tdonline">
            <tr>
                <td style="width: 100%; height: 100%" colspan="4"> 
                    <div id="map_canvas" style="width: 100%; height: 100%"></div>
                </td>
            </tr>
            <tr >
                <td width="100%" class="tdPagina4">
                    <input id="t_lat" type="hidden" value="<%=mlat%>"/>
                    <input id="t_lon" type="hidden" value="<%=mlng%>"/>
                    <input id="t_zoo" type="hidden" value="13"/>
                </td>
                <td style="height: 15px;" align="center"> 
                    <%if (edit) {%>
                    <input class="boton" id="b_guarda" type="button" title="Guardar" name="Guardar" value="Guardar" onclick="save_position()" >
                    <%}%>
                </td>
                <td style="height: 15px;" align="center">
                    <input class="boton" id="b_cargar" type="button" title="Centrar" name="Centrar" value="Centrar" onclick="center_position()" >
                </td>
                <td style="height: 15px;" align="center"> 
                    <input class="boton" id="b_cerrar" type="button" title="Cerrar" name="Cerrar" value="Cerrar" onclick="close_positicion()" >
                </td>
            </tr>
        </table>
    </body>
</html>
